import { NextResponse } from "next/server";
import { connectToDatabase } from "@/lib/mongodb";
import { ObjectId, WithId } from "mongodb";
// 定义请求数据的类型
interface RequestBody {
    message: string;
}

// 定义响应数据的类型
interface ResponseBody {
    message?: string;
    error?: string;
}

export async function POST(request: Request): Promise<NextResponse<ResponseBody>> {
    try {
        // 从请求体中获取 JSON 数据
        const { message } = await request.json();

        // 检查是否有提供字符串
        if (typeof message === "string") {
            const { db } = await connectToDatabase();

            const insertOneRes = await db.collection("text").insertOne({ message });

            if (insertOneRes.acknowledged) {
                // 返回相同的字符串作为响应
                return NextResponse.json({ message, _id: insertOneRes.insertedId }, { status: 200 });
            } else {
                return NextResponse.json({ message: "添加失败" }, { status: 202 });
            }
        } else {
            // 返回错误响应，提示无效输入
            return NextResponse.json({ message: "Invalid input, please provide a string." }, { status: 400 });
        }
    } catch (error) {
        // 返回服务器错误，并设置状态码为 500
        return NextResponse.json({ error: "Internal server error." + error }, { status: 500 });
    }
}

export interface TextData {
    message: string;
    _id: string;
}

export async function GET(): Promise<
    NextResponse<{
        list?: TextData[];
        error?: string;
    }>
> {
    try {
        const { db } = await connectToDatabase();

        const allTextRes = await db.collection("text").find<TextData>({},{sort:{_id:-1}}).toArray();

        // 返回文件中的消息内容
        return NextResponse.json({ list: allTextRes }, { status: 200 });
    } catch (error) {
        // 如果文件不存在或读取出错，返回错误消息
        return NextResponse.json({ error: "No message found or error reading file." }, { status: 500 });
    }
}

export async function DELETE(): Promise<
    NextResponse<{
        message?: number;
        error?: string;
    }>
> {
    try {
        const { db } = await connectToDatabase();

        const deleteRes = await db.collection("text").deleteMany({});

        // 返回文件中的消息内容
        return NextResponse.json({ message: deleteRes.deletedCount }, { status: 200 });
    } catch (error) {
        // 如果文件不存在或读取出错，返回错误消息
        return NextResponse.json({ error: "操作失败" }, { status: 500 });
    }
}
